import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import dayjs from 'dayjs'
import {
  getBlogDetailXhr,
  postPublishCommentXhr,
  getCommentListXhr,
} from '~/api/index'
import { getUserInfo } from '~/utils/crypto'
import { DEFAULT_AVATAR } from '~/const/index'
import toast from '~/utils/toast'

interface CommentProps {
  comment: any
}

const Comment: React.FC<CommentProps> = ({ comment }) => {
  return (
    <div className="mb-6 glass-card p-4">
      <div className="flex items-start gap-3">
        <img
          src={comment.user_avatar || DEFAULT_AVATAR}
          alt="avatar"
          className="w-10 h-10 rounded-full"
        />
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <span className="font-medium">{comment.user_nickname}</span>
            <span className="text-xs text-gray-500">{comment.comment_ip}</span>
            <span className="text-xs text-gray-500">
              {dayjs(comment.created_at).format('YYYY-MM-DD HH:mm')}
            </span>
          </div>
          <p className="text-gray-700 dark:text-gray-300">{comment.content}</p>
        </div>
      </div>
      {/* {comment.replies && comment.replies.length > 0 && (
        <div className="ml-12 mt-4">
          {comment.replies.map((reply: any) => (
            <div key={reply.id} className="mb-4">
              <div className="flex items-start gap-3">
                <img
                  src={reply.user_avatar || DEFAULT_AVATAR}
                  alt="avatar"
                  className="w-8 h-8 rounded-full"
                />
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <span className="font-medium">{reply.user_nickname}</span>
                    <span className="text-xs text-gray-500">
                      {reply.comment_ip}
                    </span>
                    <span className="text-xs text-gray-500">
                      {dayjs(reply.createdAt).format('YYYY-MM-DD HH:mm')}
                    </span>
                  </div>
                  <p className="text-gray-700 dark:text-gray-300">
                    {reply.content}
                  </p>
                </div>
              </div>
            </div>
          ))}
        </div>
      )} */}
    </div>
  )
}

const ArticleContent = React.memo(({ content }: { content: string }) => {
  return (
    <div
      className="prose dark:prose-invert max-w-none flex-grow"
      dangerouslySetInnerHTML={{ __html: content }}
    />
  )
})

const ArticleDetailPage: React.FC = () => {
  const { id } = useParams()
  const [article, setArticle] = useState<any>(null)
  const [comments, setComments] = useState<any[]>([])
  const [commentContent, setCommentContent] = useState('')
  const [taotalComments, setTotalComments] = useState(0)
  const userInfo = getUserInfo()

  const getCommentList = async () => {
    const res = await getCommentListXhr({
      articleId: id,
      page: 1,
      pageSize: 100,
    })
    if (res.code === 200) {
      setComments(res?.data?.list || [])
      setTotalComments(res?.data?.total || 0)
    }
  }

  useEffect(() => {
    if (id) {
      // 获取文章详情
      getBlogDetailXhr(id).then((res) => {
        if (res.code === 200) {
          setArticle(res.data)
        }
      })
      // 获取评论列表
      getCommentList()
    }
  }, [id])

  const handleComment = async () => {
    if (!userInfo) {
      toast.info('请先登录')
      return
    }
    if (!commentContent.trim()) {
      toast.info('请输入评论内容')
      return
    }

    try {
      console.log('userInfo', userInfo)
      const res = await postPublishCommentXhr({
        articleId: id,
        content: commentContent,
        userId: userInfo.id,
        userName: userInfo.nickname || userInfo.username,
        userAvatar: userInfo.avatar,
      })

      if (res.code === 200) {
        toast.success('评论成功')
        setCommentContent('')
        // 获取评论列表
        getCommentList()
      }
    } catch (error) {
      toast.error('评论失败')
    }
  }

  if (!article) {
    return <div className="container px-6 py-6 text-center">加载中...</div>
  }

  return (
    <div className="container px-6">
      <article className="glass-card p-8 mb-[12px] min-h-[600px] flex flex-col">
        <h1 className="text-3xl font-bold mb-4">{article.title}</h1>
        <ArticleContent content={article?.content} />
        <div className="flex items-center justify-between pt-4 mt-4 border-t border-gray-200 dark:border-gray-700 text-sm text-gray-500">
          <div className="flex items-center gap-4">
            <div className="flex items-center">
              <img
                src={article?.authorAvatar || DEFAULT_AVATAR}
                alt="avatar"
                className="w-8 h-8 rounded-full mr-2"
              />
              <span>{article.authorName}</span>
            </div>

            <span>
              发布时间: {dayjs(article.createdAt).format('YYYY-MM-DD HH:mm')}
            </span>
          </div>
          <div className="flex items-center gap-1 text-xs text-gray-400">
            发布于: <span>{article?.publishLocation || '未知地区'}</span>
          </div>
          <div className="flex items-center gap-2">
            <i className="ri-eye-line"></i>
            <span>{article.views || 0}</span>
          </div>
        </div>
      </article>

      <div className="glass-card p-2">
        <h3 className="text-1xl font-bold mb-4">
          评论区（{taotalComments !== 0 ? taotalComments || '0' : '0'}）
        </h3>
        <div className="mb-4">
          <textarea
            value={commentContent}
            onChange={(e) => setCommentContent(e.target.value)}
            placeholder={'输入评论内容...'}
            className="w-full p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[120px] transition-all duration-200"
            rows={4}
          />
          <div className="flex justify-between items-center mt-2">
            <button
              onClick={handleComment}
              className="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition-colors"
            >
              评论
            </button>
          </div>
        </div>

        <div className="space-y-6">
          {comments?.map((comment) => (
            <Comment key={comment.id} comment={comment} />
          ))}
        </div>
      </div>
    </div>
  )
}

export default ArticleDetailPage
